package com.controller;

import com.po.Activity;
import com.po.Msg;
import com.po.Suggest;
import com.po.User;
import com.service.ActivityService;
import com.service.SuggestService;
import com.service.TypeService;
import com.service.UserService;
import com.util.GPSUtils;
import com.util.MD5Utils;
import net.sf.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.web.PageableDefault;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import javax.validation.Valid;
import java.io.IOException;
import java.util.List;

@Controller
public class TouristController {

    @Autowired
    private UserService userService;

    @Autowired
    private ActivityService activityService;

    @Autowired
    private TypeService typeService;

    @Autowired
    private SuggestService suggestService;

    @GetMapping("/")
    public String index(@PageableDefault(size = 2, sort = {"id"}, direction = Sort.Direction.DESC) Pageable pageable, Model model, Activity activity) {
        Page<Activity> p=activityService.findAllByT1(pageable);
        model.addAttribute("num",p.getTotalElements());
        model.addAttribute("page2",p);
        model.addAttribute("types", typeService.listTypeTop(5));
        model.addAttribute("recommendActivity", activityService.listRecommendActivityTop(5));
        return "index";
    }

    @GetMapping("/login")
    public String login() {
        return "login";
    }

    @PostMapping("/get_code")
    @ResponseBody
    public Msg getCode(@RequestParam("phone") String phone, HttpServletRequest request) {
        System.out.println("phone" + phone);
        User exist = userService.checkUserByPhone(phone);
        if (exist == null) {
            System.out.println("OK");
            String code = "123456";
            System.out.println("随机生成的验证码为" + code);

            //1分钟倒计时
            JSONObject time = new JSONObject();
            time.put("code", code);
            time.put("createTime", System.currentTimeMillis());
            request.getSession().setAttribute("codes", time);
            return Msg.success();
//            Msg getcode=code(user_phone,request);
//            if (getcode.getCode()== 200){
//                return Msg.success();//发送成功
//            }else if(getcode.getCode()== 301){
//                return  Msg.isv_money();//余额不足
//            }else if(getcode.getCode()== 300){
//                return  Msg.isv_over();//发送频率过快
//            }
        }
        System.out.println("用户已存在");
        return Msg.exist();//用户已存在
    }

    @PostMapping("/found_code")
    @ResponseBody
    public Msg foundCode(@RequestParam("phone") String phone, HttpServletRequest request) {
        System.out.println("phone" + phone);
        User exist = userService.checkUserByPhone(phone);
        if (exist != null) {
            System.out.println("OK");
            String code = "123456";
            System.out.println("随机生成的验证码为" + code);

            //1分钟倒计时
            JSONObject time = new JSONObject();
            time.put("code", code);
            time.put("createTime", System.currentTimeMillis());
            request.getSession().setAttribute("codes", time);
            return Msg.success();
//            Msg getcode=code(user_phone,request);
//            if (getcode.getCode()== 200){
//                return Msg.success();//发送成功
//            }else if(getcode.getCode()== 301){
//                return  Msg.isv_money();//余额不足
//            }else if(getcode.getCode()== 300){
//                return  Msg.isv_over();//发送频率过快
//            }
        }
        System.out.println("用户不存在");
        return Msg.exist();//用户不存在
    }

    /**
     * 调用生成验证码
     */
/*    public Msg code(String phone, HttpServletRequest request) {
//        String code=(int)((Math.random()*9+1)*100000)+"";
        String code="123456";
        System.out.println("随机生成的验证码为" + code);

        //1分钟倒计时
        JSONObject time = new JSONObject();
        time.put("code", code);
        time.put("createTime", System.currentTimeMillis());
        request.getSession().setAttribute("codes", time);

        //将验证码转为json格式
        Map map = new HashMap();
        map.put("code", code);
        JSONObject jsonObject = JSONObject.fromObject(map);
        String result = jsonObject.toString();//将json对象转化为json字符串
        Msg getcode= SendSmsUtil.send1(phone, "SMS_195722297", result);
        System.out.println("getcode"+getcode.getCode());
        return getcode;
    }*/
    @PostMapping("/add_user/{code}")
    @ResponseBody
    public Msg addUser(@Valid User user, @PathVariable("code") String code, HttpServletRequest request, Model model) {
        System.out.println("输入的验证码是" + code);
        JSONObject codes = (JSONObject) request.getSession().getAttribute("codes");
        System.out.println("验证码是" + codes);

        //检验验证码是否正确
        if (codes.getString("code").equals(code)) {
            //检验验证码是否过期（5分钟）测试用1分钟
            System.out.println("111");
            if ((System.currentTimeMillis() - codes.getLong("createTime")) > 1000 * 60 * 1) {
                System.out.println("222");
                return Msg.pass();//验证码已过期
            } else {
                System.out.println("333");
                user.setPassword(MD5Utils.code(user.getPassword()));
                User u = userService.saveUser(user);
                if (u == null) {
                    System.out.println("444");
                    return Msg.fail();//注册失败
                }
                System.out.println("555");
                return Msg.success();//注册成功
            }
        } else {
            System.out.println("验证码不正确");
            return Msg.error();//验证码错误
        }
    }

    @PostMapping("/found_user/{code}")
    @ResponseBody
    public Msg found(@Valid User user, @PathVariable("code") String code, HttpServletRequest request,HttpSession session) {
        System.out.println("输入的验证码是" + code);
        JSONObject codes = (JSONObject) request.getSession().getAttribute("codes");
        System.out.println("验证码是" + codes);

        //检验验证码是否正确
        if (codes.getString("code").equals(code)) {
            //检验验证码是否过期（5分钟）测试用1分钟
            System.out.println("111");
            if ((System.currentTimeMillis() - codes.getLong("createTime")) > 1000 * 60 * 1) {
                System.out.println("222");
                return Msg.pass();//验证码已过期
            } else {
                System.out.println("333");
                User user1= userService.checkUserByPhone(user.getPhone());
                user1.setPassword(MD5Utils.code(user.getPassword()));
                User u = userService.saveUser(user1);
                if (u == null) {
                    System.out.println("444");
                    return Msg.fail();//注册失败
                }
                System.out.println("555");
                return Msg.success();//注册成功
            }
        } else {
            System.out.println("验证码不正确");
            return Msg.error();//验证码错误
        }
    }



    @PostMapping("/check_mes")
    @ResponseBody
    public Msg checkMes(@RequestParam("phone") String phone, @RequestParam("password") String password, HttpSession session){
        User user = userService.checkUserByPP(phone, MD5Utils.code(password));
        if (user != null) {
            session.setAttribute("user",user);
            return Msg.success();
        } else{
            System.out.println("333");
            User exist = userService.checkUserByPhone(phone);
            if (exist == null) {
                System.out.println("444");
                return Msg.none();//账号不存在
            }else{
                System.out.println("555");
                return Msg.fail();//密码错误
            }
        }
    }

    @GetMapping("/get_place")
    @ResponseBody
    public Msg get_place(@RequestParam("place")String place, HttpSession session) throws IOException {
        String p= GPSUtils.addressResolution(GPSUtils.getLocationAddr(place));
        session.setAttribute("p",p);
        return Msg.success();
    }




    @PostMapping("/admin_login")
    @ResponseBody
    public Msg admin_login(@RequestParam("phone") String phone, @RequestParam("password") String password,HttpSession session){
        User user=userService.checkUserByPP(phone,MD5Utils.code(password));
        if(user!=null){
            if(user.getState()==9){
                session.setAttribute("admin",user);
                return Msg.success();//是管理员
            }else {
                return Msg.fail();//此账号无权限
            }
        }else{
            return Msg.none();//账号不存在
        }
    }

    @PostMapping("/lead_login")
    @ResponseBody
    public Msg lead_login(@RequestParam("phone") String phone, @RequestParam("password") String password){
        User user=userService.checkUserByPP(phone,MD5Utils.code(password));
        if(user!=null){
            if(user.getState()==1){
                return Msg.success();//是负责人
            }else {
                return Msg.fail();//此账号无权限
            }
        }else{
            return Msg.none();//账号不存在
        }
    }

    @GetMapping("/end")
    public String end(Pageable pageable, Model model){
        Page<Activity> activities=activityService.findAllByEnd(pageable);
        model.addAttribute("page2",activities);
        model.addAttribute("num",activities.getTotalElements());
        return "end";
    }

    @GetMapping("/suggest")
    public String suggest(){
        return "suggest";
    }

    @GetMapping("/input_suggest")
    @ResponseBody
    public Msg activity(@RequestParam String content,HttpSession session){
        User u= (User) session.getAttribute("user");
        if(u==null){
            return Msg.error();
        }else {
            System.out.println("111111");
            Suggest suggest = new Suggest();
            suggest.setUser(u);
            suggest.setContent(content);
            suggestService.save(suggest);
            System.out.println("@22222");
            return Msg.success();
        }
    }

}
